package com.base.common.converter;

import java.util.ArrayList;
import java.util.List;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.operamasks.faces.annotation.Convert;
import org.operamasks.faces.annotation.DefineConverter;
import org.operamasks.faces.annotation.Format;

import com.base.commons.SpringBeanHolder;
import com.base.organization.entity.DepartmentalUnit;
import com.base.organization.service.IDepartmentalUnitDAO;

/**
 * 用于将部门id转换成部门名称的转换类
 * 
 * 
 */
@DefineConverter(id = "departmentNameFormatter")
public class DepartmentNameConverter implements Converter {
	private final static Log logger = LogFactory
			.getLog(DepartmentNameConverter.class);
	private IDepartmentalUnitDAO depDao = SpringBeanHolder
			.getBean("departmentalUnitDAO");

	@Format
	public String format(Object value) {
		if (value == null || "".equals(value.toString()))
			return "";
		String userId = value.toString();
		String[] temp = userId.split(",");
		List<Integer> ids = new ArrayList<Integer>(temp.length);
		StringBuilder names = new StringBuilder();
		for (String id : temp) {
			try {
				ids.add(Integer.parseInt(id));
			} catch (NumberFormatException e) {
				names.append(id);
				names.append(",");
				continue;
			}
		}
		List<DepartmentalUnit> deps = depDao.findByIds(ids);
		if (deps.isEmpty())
			return "";
		StringBuilder sb = new StringBuilder();
		for (DepartmentalUnit du : deps) {
			sb.append(du.getName());
			sb.append(",");
		}
		sb.append(names);
		return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
	}

	@Convert
	public Object convert(String value) {
		return null;
	}

	@Override
	public Object getAsObject(FacesContext context, UIComponent component,
			String value) {
		return null;
	}

	@Override
	public String getAsString(FacesContext context, UIComponent component,
			Object value) {
		if (value == null || "".equals(value.toString()))
			return "";
		String userId = value.toString();
		String[] temp = userId.split(",");
		List<Integer> ids = new ArrayList<Integer>(temp.length);
		StringBuilder names = new StringBuilder();
		for (String id : temp) {
			try {
				ids.add(Integer.parseInt(id));
			} catch (NumberFormatException e) {
				names.append(id);
				names.append(",");
				continue;
			}
		}
		List<DepartmentalUnit> deps = depDao.findByIds(ids);
		if (deps.isEmpty())
			return "";
		StringBuilder sb = new StringBuilder();
		for (DepartmentalUnit du : deps) {
			sb.append(du.getName());
			sb.append(",");
		}
		sb.append(names);
		return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
	}

}
